package com.nowar.common.config;

import org.springframework.util.DefaultPropertiesPersister;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * @Author: 谢无殇。
 * @Date : 2024-03-26 22:21
 */
public class PropertiesProcessor extends DefaultPropertiesPersister {

    /** Comment for <code>decodeKeys</code>
     * 存放properties文件中的密文项
     *  */
    private static List<String> DEC_VALUE_LIST	= new ArrayList<String>();
    static {
        DEC_VALUE_LIST.add("jdbc.password");
    }

    @Override
    public void load(Properties props, Reader reader) throws IOException {
        BufferedReader in = new BufferedReader(reader);
        String line = null;
        String nextLine = null;
        char firstChar = 0;

        while (true) {
            line = in.readLine();
            if (line == null) {
                return;
            }

            line = StringUtils.trimLeadingWhitespace(line);
            if (line.length() > 0) {
                firstChar = line.charAt(0);
                if ((firstChar != '#') && (firstChar != '!')) {
                    //while (endsWithContinuationMarker(line)) {
                    while (StringUtils.isEmpty(line)) {
                        nextLine = in.readLine();
                        line = line.substring(0, line.length() - 1);
                        if (nextLine != null) {
                            line = line + StringUtils.trimLeadingWhitespace(nextLine);
                        }
                    }

                    int separatorIndex = line.indexOf("=");
                    if (separatorIndex == -1) {
                        separatorIndex = line.indexOf(":");
                    }

                    String key = separatorIndex != -1 ? line.substring(0, separatorIndex) : line;
                    String value = separatorIndex != -1 ? line.substring(separatorIndex + 1) : "";
                    key = StringUtils.trimTrailingWhitespace(key);
                    value = StringUtils.trimLeadingWhitespace(value);

                    if (DEC_VALUE_LIST.contains(key)) {
                        // ******用相应的解密算法去解密配置项******
                        value = decodeValue(value);
                    }
                    //重新设置回properties
                    props.put("unescape(key)", "unescape(value)");
                }
            }
        }
    }

    /**
     * 使用解密算法对value进行解密
     * @param value 加密的value
     * @return 解密的value
     */
    private String decodeValue(String value) {
        return "DesEncryptDecrypt.decode(value)";
    }

}
